import { Component, OnInit } from '@angular/core';
import { Singlepage } from '../../model/singlepage';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Router, ActivatedRoute } from '@angular/router';
import { SinglepageService } from '../../service/singlepage.service';

@Component({
  selector: 'app-editsinglepage',
  templateUrl: './editsinglepage.component.html',
  styleUrls: ['./editsinglepage.component.css']
})
export class EditsinglepageComponent implements OnInit {
  singlepage:Singlepage;
  parm:string;
  selectedFile:string;
  canfig:any;
  constructor(
    private http:HttpClient,
    private router:Router,
    private routerinfo:ActivatedRoute,
    private singlepageservice:SinglepageService
  ) {
    this.parm = this.routerinfo.snapshot.params['id'];
   }

  ngOnInit() {
    if(this.parm=='add'){
      this.singlepage = new Singlepage();
    }else{
      this.getSinglepage(this.parm);
    }
  }

  goBack(){
    this.singlepage = new Singlepage();
    this.router.navigate(['uploadpage']);
  }

  save(){
    console.dir(this.singlepageservice);
    if(this.parm=='add'){
      this.addSinglepage();
    }else{
      this.updateSinglepage();
    }
  }


  addSinglepage(){
    this.singlepageservice.addSinglepage(this.singlepage)
    .then((flag:boolean)=>{
      if(flag==true){
        alert('成功！');
        this.goBack();
      }else{
        alert('失败!');
      }
    })
  }

  updateSinglepage(){
    this.singlepageservice.updateSinglepage(this.singlepage)
    .then((flag:boolean)=>{
      if(flag==true){
        this.goBack();
      }else{
        alert("保存异常，请重试!");
      }
    })
  }

  getSinglepage(id:string){
    this.singlepageservice.getSinglepage(id)
    .then((data:Singlepage)=>{
      if(data){
        this.singlepage = data;
      }else{
        alert("通讯异常，请刷新后重试!");
      }
    })
  }


  onFileChanged(event) {
    this.selectedFile = event.target.files[0];
    //this.onUpload();
  }

  onUpload() {
    // upload code goes here

    const uploadData = new FormData();
  uploadData.append('file', this.selectedFile);
  this.http.post('http://localhost/manage/fileUpload',uploadData).subscribe(
    (data:any)=>{
      //alert(data);
      //console.log(JSON.stringify(data));
      let host="http://localhost/";
      this.singlepage.img=host+data.pic;
    },(err:HttpErrorResponse)=>{
      console.log(err.message);
    }
  )

  }

}
